const log = require('../../util/log')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = require('../chromeMng.20180824').client;

async function getTaobaoItems(obj) {
  obj = obj || {}
  if (!obj.q) {
    return new Promise(resolve => {
      resolve([])
    })
  }
  log('getting taobao items', obj)
  var {result} = await Runtime.evaluate({expression: 'location.href'})
  if (result.value == 'https://pub.alimama.com/index.htm') {
    return step2(obj)
  }
  Page.navigate({
    url: 'https://pub.alimama.com/index.htm'
  })
  return new Promise(resolve => {
    setTimeout(() => {
      getTaobaoItems(obj).then(result => {
        resolve(result)
      })
    }, 1000)
  })
}

async function step2(obj) {
  log('getting taobao items step 2', obj)
  var {result} = await Runtime.evaluate({expression: 'location.href'})
  if (result.value.indexOf('https://pub.alimama.com/promo/search/index.htm') != -1) {
    return step3(obj)
  }
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#q")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        })
      }, 1000)
    })
  }
  await Runtime.evaluate({expression: 'document.querySelectorAll("#q")[0].value="' + obj.q + '"'})
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#q")[0].value'})
  if (result.value != obj.q) {
    return new Promise(resolve => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        })
      }, 1000)
    })
  }
  await Runtime.evaluate({expression: 'document.querySelectorAll("button.btn.btn-brand.search-btn")[0].click()'})
  return new Promise(resolve => {
    setTimeout(() => {
      step2(obj).then(result => {
        resolve(result)
      })
    }, 1000)
  })
}

async function step3(obj) {
  log('getting taobao items step 3', obj)
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".desc")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 1) {
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".desc")[0].innerText'})
    if (result.value == '抱歉，没有找到相关商品') {
      return new Promise(resolve => {
        resolve([])
      })
    }
  }
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("div.block-search-box.tag-wrap")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        step3(obj).then(result => {
          resolve(result)
        })
      }, 1000)
    })
  }
  var list = []
  for (var i = 0; i < cnt; i++) {
    var prefix = 'document.querySelectorAll("div.block-search-box.tag-wrap")[' + i + '].'
    var item = {}
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("a.search-box-img")[0].href'})
    if (!/http:\/\/item.taobao.com\/item.htm\?id=\d+/.test(result.value)) {
      log('不能识别的url: ' + result.value)
      return new Promise(resolve => {
        setTimeout(() => {
          step3(obj).then(result => {
            resolve(result)
          })
        }, 1000)
      })
    }
    item.id = result.value.substring('http://item.taobao.com/item.htm?id='.length)
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].attributes["data-src"]'})
    if (result.type != 'undefined') {
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].attributes["data-src"].value'})
      item.img = result.value
    } else {
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].src'})
      item.img = result.value
    }
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("a.color-m")[0].title'})
    item.title = result.value
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("span.integer")[0].innerText'})
    item.price = result.value.replace(/,/i, '') + '.'
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("span.decimal")[0].innerText'})
    item.price += result.value
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("span.fr>span>span")[0].innerText'})
    item.sale = result.value
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("span.shop-hd>a>span")[0].innerText'})
    item.shopName = result.value
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("a.search-box-img")[0].href'})
    item.link = result.value
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("span.integer")[1].innerText'})
    item.rate = result.value + '.'
    var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("span.decimal")[1].innerText'})
    item.rate += result.value
    list.push(item)
  }
  return new Promise(resolve => {
    resolve(list)
  })
}

module.exports = getTaobaoItems
